package com.example.li_han.servlet;

import com.example.li_han.pojo.News;
import com.example.li_han.service.NewsService;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@WebServlet(name = "GetAllNews", value = "/GetAllNews")
//获取所有新闻
public class GetAllNews extends HttpServlet {
    private String message;
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //1.获取用户提交的数据
        String page = request.getParameter("page");
        int currentPage = 0;
        if(page==null){
            currentPage = 1;
        }else {
            currentPage = Integer.parseInt(page);
        }
        String pageSizeStr = request.getParameter("pageSize");
        int pageSize = 10; // 默认每页10条
        if (pageSizeStr != null && !pageSizeStr.trim().isEmpty()) {
            pageSize = Integer.parseInt(pageSizeStr);
        }        //2.调用业务逻辑，完成查询功能
        NewsService newsService = new NewsService();
        List<News> list =  newsService.getAllNews(currentPage,pageSize);

        int total = newsService.getTotalNewsCount();
        //3.响应给前端,JSON数据
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","查询成功");
        map.put("total",total);//总行数
        map.put("data",list);

        Gson gson = new Gson();
        String json = gson.toJson(map);
        response.getWriter().write(json);


    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    }

}